package com.qishao.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qishao.execl.ExeclSubject;
import com.qishao.listener.ExeclSubjectListener;
import com.qishao.model.EduSubject;
import com.qishao.mapper.EduSubjectMapper;
import com.qishao.query.SubjectQuery_;
import com.qishao.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qishao.service_base.error.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.security.auth.Subject;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author xushaoqi
 * @since 2021-11-02
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    private static final Logger LOG = LoggerFactory.getLogger(EduSubjectServiceImpl.class);

    @Autowired
    private EduSubjectMapper eduSubjectMapper;

    @Override
    public void batchExeclSubject(MultipartFile file,EduSubjectService subjectService) {
      try {
          //获取文件输入流
          InputStream inputStream = file.getInputStream();

          //调用EasyExecl中的read方法读取文件中的内容
          EasyExcel.read(inputStream, ExeclSubject.class,new ExeclSubjectListener(subjectService)).sheet().doRead();
      }catch (Exception e){
        throw new CustomException("20001","导入课程分类失败！失败原因： "+e);
      }

    }

    @Override
    public List<EduSubject> subjectList() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(SubjectQuery_.PARENTID,"0");
        List<EduSubject> eduSubjects1 = baseMapper.selectList(wrapper);

        eduSubjects1.forEach( subject -> {
                getChildren(subject);
        });
        LOG.info("=========eduSubject1========="+ JSON.toJSONString(eduSubjects1));
        return eduSubjects1;
    }


    private void getChildren(EduSubject subject){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(SubjectQuery_.PARENTID,subject.getId());
        subject.setChildren(baseMapper.selectList(wrapper));
    }

}
